const respJson = require("../../utils/respJson")
const userModel = require("../../db/user")
const writeErr = require("../../utils/writeErr")
const bcryptjs = require('bcryptjs')
const jwt = require('jsonwebtoken')
const path = require('path')
const {
    readFileSync
} = require('fs')


module.exports = {
    //获取用户信息
    async getinfo(req, resp) {
        //接受传递来的id
        let {
            userId
        } = req.params
        //根据id获取用户信息
        //用promise修改数据库操作
        try {
            let docs = await userModel.findOne({
                _id: userId
            })
            if (!docs) {
                xy(resp, 405, '用户id有误！')
                return
            }
            respJson(resp, 200, '查询成功！', {
                username: docs.username,
                email: docs.email,
                tel: docs.tel,
                createdAt: +new Date(docs.createdAt),
                updatedAt: +new Date(docs.updatedAt)
            })
        } catch (err) {
            writeErr(err)
            xy(resp, 501, '系统繁忙，稍后再试！')

        }
    },

    //登录处理
    async login(req, resp) {
        let {
            username,
            password
        } = req.body
        console.log(req.body, 333);
        if (!username || !password) {
            respJson(resp, 401, '数据不能为空！')
            return
        }

        //用promise修改
        try {
            let docs = await userModel.findOne({
                username
            })
            if (!docs) {
                respJson(resp, 403, '用户名或密码错误！')
                return
            }
            if (!bcryptjs.compareSync(password, docs.password)) {
                respJson(resp, 403, '用户名或密码错误！')
                return
            }

            //拼接配置文件路径
            let configFilePath = path.join(__dirname, '../', '../', 'config', 'config.json')
            let salt = JSON.parse(readFileSync(configFilePath, 'utf-8')).tokenSalt
            respJson(resp, 200, '登录成功', {
                username: docs.username,
                userId: docs._id,
                token: jwt.sign({
                    userId: docs._id,
                    username: docs.username,
                    startTime: +new Date(),
                    expires: 7200000
                }, salt)
            })
        } catch (err) {
            writeErr(err)
            respJson(resp, 501, '系统繁忙，稍后再试！')
        }
    },

    //注册处理
    async register(req, resp) {
        let {
            username,
            password,
            email,
            tel
        } = req.body
        if (!username || !password || !email || !tel) {
            respJson(resp, 401, '数据不能为空')
            return
        }

        //用promise修改
        try {
            let docs = await userModel.findOne({
                username
            })
            if (docs) {
                respJson(resp, 402, '用户名已被占用！')
                return
            }
            try {
                docs = await userModel.insertMany({
                    username,
                    password: bcryptjs.hashSync(password, 10),
                    email,
                    tel
                })
                respJson(resp, 200, '注册成功！')
            } catch (err) {
                writeErr(err)
                respJson(resp, 502, '系统繁忙，稍后重试！')
            }
        } catch (err) {
            writeErr()
            respJson(resp, 501, '系统繁忙，稍后再试！')
        }
    }
}